<template>
  <el-container v-loading="loading">

    <el-header>
      <h5 class="content-header">图片上传</h5>

    </el-header>
    <el-main>

      <div class="image-list">
        <div class="list-default-img" v-show="isPhoto" @click.stop="addPic">

          <div>点击此处拍照或者选择照片</div>
          <input type="file" accept="image/*" ref="f1" @click="onSelectFile" @change="onFileChange"
                 style="display: none;" multiple>
        </div>
        <div class="list-ul" v-show="!isPhoto">
          <div style="position: relative" :class="[ iu.status === 1 ?'dimbacki':'']" v-for="(iu, index) in imgUrls">
            <i class="el-icon-error list-item-unselect" v-if="iu.status === 0 || iu.status === 2" @click="unselect(index,iu)"></i>
            <el-image class="list-item " :class="[iu.status === 1? 'dim' : '' ]" fit="cover" :src="iu.b64"
                      @click='previewImage(iu.b64)' :preview-src-list="previewImages"></el-image>
            <i class="el-icon-success progress progress-success" v-if="iu.status === 1"></i>
            <i class="el-icon-error progress progress-fail" v-if="iu.status === 2"></i>
          </div>
          <el-image class="list-item" :src="require('../assets/add-img.png')" @click.stop="addPic"></el-image>
        </div>
      </div>
    </el-main>

    <el-footer>
      <el-button type="primary" @click="postAllFile">确定</el-button>
      <el-button type="danger" @click="closePage">关闭页面</el-button>
    </el-footer>

  </el-container>

</template>

<script>

  import lrz from 'lrz';

  export default {
    name: 'Upload',
    data: function () {
      return {
        imgUrls: [],

        isPhoto: true,

        isModify: false,
        previewImg: '',
        isPreview: false,
        uploadApi: '',
        slide: [],
        loading: false
      }
    },

    created() {
       this.uploadApi = 'https://xzfyyh.bitsys.com.cn/adminproxy/upload'+ window.location.search;
     // this.uploadApi = 'http://172.16.140.178:8888/adminproxy/upload?trial_id=1&user_id=1';
     // this.uploadApi = 'http://172.16.140.178:8888/adminproxy/upload'+ window.location.search;
     // this.uploadApi = 'http://192.168.0.106/upload'
      document.title = '上传附件';



    },

    watch: {
      imgUrls: 'toggleAddPic'
    },

    mounted() {

    },
    computed: {
      previewImages() {
        let ret = [];
        this.imgUrls.forEach((v, i) => {
          ret.push(v.b64);
        });
        return ret;
      }
    },

    methods: {

      closePage(){

        let ret = window.confirm('确定关闭页面？')
        if (ret) {
          window.history.back(-1);
        }
      },

      onSelectFile() {



        this.$refs.f1.value = '';
      },

      /**
       * 取消选择
       * **/
      unselect(index, item) {

        this.imgUrls.splice(index, 1);
      },

      /**
       * 一键上传
       */
      async postAllFile() {

        if (this.imgUrls.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择文件'
          })
        } else {
          this.loading = true;
          let imgUrlsNew = [];
          let promiseArr = [];

          let p = null;

          for (let i = 0;i< this.imgUrls.length;i++) {
            p = this.imgUrls[i];
            if (p.status === 0) {
              promiseArr.push( this.postFile(p.file))
            } else {
              promiseArr.push(Promise.resolve(p.status))
            }
          }

          try{
            let [successCount , failCount] = [0,0];
            let values = await Promise.all(promiseArr.map(p=> p.catch(e=>e)))
            values.map((res,i) =>{
              if (typeof (res) !== 'number') {
                if (res.status === 200 && res.data && res.data.code === 1) {
                  this.imgUrls[i].status = 1;//上传成功
                  successCount++;
                } else {
                  this.imgUrls[i].status = 2;//上传失败
                  failCount++;
                }
              }
              imgUrlsNew.push(this.imgUrls[i])
            });

              this.imgUrls = imgUrlsNew;

              this.$message({
                type: failCount>0?'warning':"success",
                message: `上传完成，成功：${successCount}个，失败：${failCount}个`
              })
          }catch (e) {
            this.$message({
              type: "error",
              message:e
            });
          }
          this.loading = false;


        }
      },

      /**
       * 单个上传
       * @param file
       * @returns {Promise<AxiosResponse<any>>}
       */
      postFile(file) {
        let forms = new FormData();
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        forms.append('file', file)

        return this.$http.post(this.uploadApi, forms, configs)

      },
      toggleAddPic: function () {
        let vm = this;
        vm.isPhoto = vm.imgUrls.length < 1;
      },
      addPic: function (e) {

       this.$refs.f1.click();
       return false;
      },

      onFileChange: function (e) {

        var files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;

        console.log(files);
        this.createImage(files);


      },

      createImage: function (file) {
        for(let i = 0;i< file.length;i++){
          //alert(file[i].size)
          lrz(URL.createObjectURL(file[i]),{}).then(
            rst=>{
              //console.log(rst)
              let reader = new FileReader();
              reader.readAsDataURL(rst.file)
              reader.onload = (e) => {
                console.log(e)
               // alert(rst.file.size)
                this.imgUrls.push({b64: e.target.result, file: rst.file, status: 0})
              }
            }
          )


        }
      },
      previewImage(src) {

      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  li {
    list-style-type: none
  }

  .content-header {
    text-align: left;
    font-size: 1.5rem;
    background-color: #eee;
    margin: 0 0 .5rem;
    color: #9a9a9a;
    padding: .5rem;
  }

  .list-default-img {
    line-height: 5rem;
    font-size: 1.5rem;
    border: .1rem dashed #eee;
    color: #9a9a9a;
  }

  .list-ul {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    /*grid-template-rows: repeat(3, 1fr);*/
    grid-gap: .5rem;
  }

  .list-item {
    height: 0;
    width: 100%;
    padding-bottom: 100%;

  }

  .progress {
    z-index: 10;
  }

  .progress-success {
    color: #13ce66;
  }

  .progress-fail {
    color: red;
  }

  .dim {
    /*opacity: 0.4;*/
  }

  .dimback {
    background: #000;
  }

  .list-item-unselect {
    color: rgba(255, 60, 0, 0.89);
    position: absolute;
    font-size: 2rem;
    right: 0;
    z-index: 10;

  }
</style>
<style>
  .list-item img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
</style>
